package cn.shenlong.portal.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.shenlong.common.Page;
import cn.shenlong.common.Pagination;
import cn.shenlong.portal.domain.User;
import cn.shenlong.portal.mapper.UserMapper;
import cn.shenlong.portal.service.UserService;
import cn.shenlong.util.StrUtils;

@Service("UserService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public Page findPageListByCriteria(User user,
			Map<String, Object> otherParm, Integer pageNo, Integer pageSize) {
		Page p = new Page();
		List<User> userList = userMapper.findPageListByCriteria(
				initUserParm(user, otherParm),
				initRowBounds(pageSize, pageNo, p));
		Long count = userMapper.findCountByCriteria(initUserParm(user,
				otherParm));
		p.setList(userList);
		p.setTotalCount(count.intValue());
		return p;

	}

	private Map<String, Object> initUserParm(User user,
			Map<String, Object> otherParm) {
		Map<String, Object> parm = new HashMap<String, Object>();
		if (otherParm != null) {
			parm.putAll(otherParm);
		}
		if (user == null) {
			return parm;
		} else {
			parm.put("userId", user.getUserId());
			parm.put("userName", user.getUserName());
			parm.put("registName", StrUtils.replaceBlank(user.getRegistName()));
			parm.put("password", user.getPassword());
			return parm;
		}

	}

	private RowBounds initRowBounds(Integer pageSize, Integer pageNo, Page p) {
		RowBounds rowBounds = null;
		if (pageSize == null || pageNo == null) {
			rowBounds = new RowBounds();
		} else {
			p.setPageNo(pageNo);
			p.setPageSize(pageSize);
			rowBounds = new RowBounds(p.getFirstResult(), p.getPageSize());
		}
		return rowBounds;
	}

	@Override
	public List<User> findUserByRegistName(String registName) {
		if (StringUtil.isBlank(registName)) {
			return new ArrayList<User>();
		}
		User user = new User();
		user.setRegistName(registName);
		List<User> userList = userMapper.findPageListByCriteria(
				initUserParm(user, null), new RowBounds());

		return userList;
	}

	@Override
	public void saveUser(User user) {
		userMapper.saveEntity(user);

	}

	@Override
	public void updateUser(User user) {
		userMapper.updateEntity(user);

	}

	@Override
	public User findUserById(Long userId) {
		if (userId == null) {
			return null;
		}
		return userMapper.findByPK(userId);
	}

	@Override
	@Transactional
	public void deleteUser(Long[] userIds) {
		userMapper.deleteByPKArray(userIds);

	}

}
